package com.test.service.Impl;

import java.text.ParseException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.test.dao.DynamicSpecifications;
import com.test.dao.PersonDao;
import com.test.model.Person;
import com.test.service.PersonService;

@Service
@EnableJpaAuditing
public class PersonServiceImpl implements PersonService {

	@Autowired
	private PersonDao personDao;

	@Override
	@Transactional
	public void savePerson(Person person) {
		personDao.save(person);
	}

	@Transactional
	@Override
	public void deletePerson(Person person) {
		personDao.delete(person);
	}

	@Override
	public Person getOneByIdentityNumber(String identityNumber) {
		return personDao.findOneByIdentityNumber(identityNumber);
	}

	@Override
	public Person getOneByIdentityNumberAndId(String identityNumber, String id) {
		return personDao.findByIdentityNumberAndId(identityNumber, id);
	}

	@Override
	public Person getPersonById(String id) {
		return personDao.findById(id);
	}

	@Override
	public Page<Person> getPersonListByConditions(String identityNumber, String personName, String sex,
			String birthTime, String department, int page, int size) throws ParseException {
		Specification<Person> spec = DynamicSpecifications.bySearchFilter(identityNumber, birthTime, personName, sex,
				department);
		PageRequest pageRequest = new PageRequest(page, size, new Sort(Direction.ASC, "birthTime"));
		return personDao.findAll(spec, pageRequest);
	}

}
